import {Stomp} from './stomp.min.js'
const app = getApp();
class WebSocket {

    stompClient = null;

    socketTask = null;
	connected = false;

    constructor () {
		
		console.log(JSON.stringify(app))
        /*setInterval是用来发心跳包的，而小程序没有window对象*/
        Stomp.setInterval = function (interval, f) {
            return setInterval(f, interval);
        };
        Stomp.clearInterval = function (id) {
            return clearInterval(id);
        };
    }

    /**
     * 建立websocket连接
     * @param webSocketUrl 连接地址
     */
    buildConnect (webSocketUrl) {
			if (!this.getSocketStatus()) {
				
				var that = this;
				var socketTask = uni.connectSocket({
					url: webSocketUrl,
					success: function(res) {
						console.log("success"+JSON.stringify(res))
					},
					fail:function(res){
						console.log("fail"+JSON.stringify(res))
					}
				});
				console.log("socketTask"+JSON.stringify(socketTask))
				var ws = {
					send: function (frame) {
						socketTask.send({data: frame});
					},
					close: function (frame) {
						socketTask.close(frame);
					}
				};
				var i = 0;
				
	
				console.log("soketTask" + JSON.stringify(socketTask));
				socketTask.onOpen(function (frame) {
					console.log("websocket 连接上了");
					that.connected = true;
					ws.onopen(frame)
				});
				socketTask.onMessage(function (frame) {
					ws.onmessage(frame)
				});
				socketTask.onClose(function (frame) {
					console.log("websocket 断开了，重建连接");
					
					
					
				});
				socketTask.onError(function(){
					console.log("连接发生错误，重建连接");
					setTimeout(function() {
						if(callback !== undefined)
							callback();
					}, 6000)
					
				})
				var stompClient = Stomp.over(ws);
				
				stompClient.connect({},
					function (frame) {
						console.log("The connection is successful: ", frame);
						that.socketTask = socketTask;
						that.stompClient = stompClient;
					}
				);
				
		}
        
    }
	
	isConnected() {
		return this.connected;
	}

    /**
     * 设置消息监听器
     * @param channel    频道
     * @param monitorFun 函数
     */
    setMessageMonitor (channel, monitorFun) {

		var i = 0
		// while(true) {
// 			console.log("setMessageMonitor ...."+ i++)
// 			if(this.getSocketStatus() == true || i == 10)
// 			{
				this.stompClient.subscribe(channel, monitorFun);
//				console.log("channel listener ...", channel);
		//		break;
			// }
			
		// }
		console.log("setMessageMonitor end....")
        
    }

    /**
     * 发送消息
     * @param channel 频道
     * @param header  消息头
     * @param body    消息体
     */
    sendMessage (channel, header, body) {
		console.log("sendMessage...")
        if (this.getSocketStatus()) {
            this.stompClient.send(channel, header, JSON.stringify(body));
        }
    }

    /**
     * 获取连接状态
     * @return boolean
     */
    getSocketStatus () {
        if (this.socketTask && this.socketTask.readyState) {
            return this.socketTask.readyState === 1 ? true : false;
        } else {
            console.log("websocket 连接还未建立");
        }
    }

    /**
     * 关闭连接
     */
    close () {
        if (this.getSocketStatus()) {
            this.stompClient.disconnect();
            this.stompClient = null;
            this.socketTask = null;
        }
    }
}

export {
    WebSocket
}